package com.yuexunit.finance.eqianbao.action.v1;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yuexunit.core.ConfigPropertites;
import com.yuexunit.finance.common.httpclient.HttpClientHelper;
import com.yuexunit.finance.context.FinanceSessionContext;
import com.yuexunit.finance.encrytSHA235.Secretkey;
import com.yuexunit.finance.esign.action.v1.EqianbaoActionApi;
import com.yuexunit.finance.esign.action.v1.model.output.EqbResult;
import com.yuexunit.finance.member.entity.EnterpriseEntity;
import com.yuexunit.finance.member.entity.lexicon.AuthenticationEnum;
import com.yuexunit.finance.member.service.EnterpriseService;
import com.yuexunit.inject.ComponentFactory;
import com.yuexunit.inject.annotation.Implements;
import com.yuexunit.persist.annotation.Transactional;

import net.sf.json.JSONObject;

/**
 * @version 创建时间：2017年5月16日 下午2:18:38
 * @author wenwenlong 类说明
 */
@Implements(EqianbaoActionApi.class)
public class EqianbaoActionApiImpl implements EqianbaoActionApi {

	public static Logger logger = LoggerFactory.getLogger(EqianbaoActionApiImpl.class);
	private EnterpriseService enterpriseService = ComponentFactory.loadClass(EnterpriseService.class);

	@Override
	@Transactional
	public EqbResult informationCheck(Long enterpriseId, String unitTypeId, String scardType, String enterpriseName, String regNo,
			String province, String city, String district, String contactAddress, String businessTimeLimit,
			String codeUSC, String certificate, String sUserType, String legalPerson, String legalIdcard,
			String legalArea, String procurator, String procuratorIdcard, String procuratorPeriod, String creditCard,
			String subbranch, String depositBank, String prcptcd) {
		EqbResult result = new EqbResult();
		
		if (null == enterpriseId) {
			enterpriseId = FinanceSessionContext.getEnterpriseId();
		}
		EnterpriseEntity ee = enterpriseService.inquireEnterprise(enterpriseId);
		
		if (ee.getAuthentication() == AuthenticationEnum.TOPAY_ACFAILED && ee.getToPayCount() <= 5) {
			String ep = enterpriseName.replace("（", "(").replace("）", ")");
			result.setErrorCode("0");
			result.setMsg("");
			toPay(ee.getEnterpriseId(), ep, creditCard, subbranch, depositBank, province, city, ee.getServiceId(), prcptcd);
		} else {
			String url = ConfigPropertites.getProperties("esign_url") + "/realname/rest/external/organ/infoAuth";		
			String projectSecret = ConfigPropertites.getProperties("PROJECT_SECRET");
			String projectId = ConfigPropertites.getProperties("PROJECTID");
			String priseName=enterpriseName.replace("（", "(").replace("）", ")");
			JSONObject params=new JSONObject();
			params.put("name", priseName);//企业名称
			params.put("codeORG", certificate);//社会统一信用代码，codeORG、codeUSC选填其中之一
			params.put("codeUSC", codeUSC);//社会统一信用代码，codeORG、codeUSC选填其中之一
			params.put("legalName", legalPerson);//法人姓名
			params.put("legalIdno", legalIdcard);//法人身份证号码
			String requestJson = params.toString();

			String signature = Secretkey.encrytSHA256(requestJson, projectSecret);
			Map<String, String> headMap = new HashMap<>();
			headMap.put("X-timevale-project-id", projectId);
			headMap.put("X-timevale-signature", signature);
			System.out.println("params:"+requestJson);
			
			String responseText = HttpClientHelper.httpTest(url, requestJson,headMap);

			JSONObject paramObj = JSONObject.fromObject(responseText);
			String serviceId = "";
			String errCode = paramObj.get("errCode").toString();
			String msg = paramObj.get("msg").toString();
			logger.info("infoAuth requestJson" + "=" + requestJson);
			logger.info("infoAuth ++++++++++++++++++" + responseText + enterpriseName);
			logger.info("infoAuth ++++++++++++++++++" + errCode + ":" + msg);
			result.setErrorCode(errCode);
			result.setMsg(msg);
			if ("0".equals(errCode)) {
				serviceId = paramObj.get("serviceId").toString();
				ee.setServiceId(serviceId);
				ee.setToPayCount(0);
				ee.setAuthentication(AuthenticationEnum.INAUTHENTICATION);
				ee.setErrorMessage(msg);
				enterpriseService.updateEnterprise(ee);
				toPay(ee.getEnterpriseId(), priseName, creditCard, subbranch, depositBank, province, city, serviceId, prcptcd);
			} else {
				ee.setAuthentication(AuthenticationEnum.NAMEREJECTION);
				ee.setErrorMessage(msg);
				enterpriseService.updateEnterprise(ee);
			}
		}
		

		return result;
	}

	/**
	 * @Title: infoAuth 企业对公打款 步骤2：打款
	 * @param enterprise
	 *            企业对象
	 * @return: String
	 */

	@Transactional
	private void toPay(Long enterpriseId, String priseName, String creditCard, String subbranch, String depositBank, String province,
			String city, String serviceId, String prcptcd) {
		String url = ConfigPropertites.getProperties("esign_url") + "/realname/rest/external/organ/toPay";
		String projectSecret = ConfigPropertites.getProperties("PROJECT_SECRET");
		String projectId = ConfigPropertites.getProperties("PROJECTID");
		String notify = ConfigPropertites.getProperties("notify");
		// Date da = DateUtils.addDateField(DateUtils.now(), Calendar.HOUR, 2);
		// SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd
		// HH:mm:ss");
		// String promptTime=dateFormat.format(da);
		JSONObject params = new JSONObject();
		EnterpriseEntity ee = enterpriseService.inquireEnterprise(enterpriseId);

		params.put("name", priseName.trim());// 对公账户户名
		params.put("cardno", creditCard.replaceAll(" ", "").trim());// 企业对公银行账号

		params.put("subbranch", subbranch.trim());// 企业银行账号开户行支持全称
		params.put("bank", depositBank.trim());// 企业银行账号开户行名称，支持银行列表
		params.put("provice", province);// 企业银行账号开户行所在省份，支持省
		params.put("city", city);// 企业银行账号开户行所在市，支持市
		params.put("prcptcd", prcptcd);// 企业用户对公账户所在的开户行的大额行号；请参考 3 支持银行列表。 列表内银行不必传入大额行号，其他银行需要传入大额行号

		params.put("notify", notify);// 打款完成通知的接收地址
		params.put("serviceId", serviceId);
		String requestJson = params.toString();
		String signature = Secretkey.encrytSHA256(requestJson, projectSecret);

		Map<String, String> headMap = new HashMap<>();
		headMap.put("X-timevale-project-id", projectId);
		headMap.put("X-timevale-signature", signature);
		
		String responseText = HttpClientHelper.httpTest(url, requestJson, headMap);
		JSONObject paramObj = JSONObject.fromObject(responseText);
		logger.info("toPay params:" + requestJson);
		logger.info("toPay responseText:" + responseText);
		String msg = paramObj.get("msg").toString();
		String errCode = paramObj.get("errCode").toString();

		long currentTime = System.currentTimeMillis();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date dates = new Date(currentTime);
		System.out.println("当前系统时间：\t" + formatter.format(dates));
		Calendar cal = Calendar.getInstance();
		cal.setTime(dates);
		int week = cal.get(Calendar.DAY_OF_WEEK) - 1;
		System.out.println("当前是星期：\t" + week);

		Calendar cals = Calendar.getInstance();
		cals.set(Calendar.HOUR_OF_DAY, 0);
		cals.set(Calendar.SECOND, 00);
		cals.set(Calendar.MINUTE, 00);
		long cals0 = cals.getTimeInMillis();
		
		Calendar cals1 = Calendar.getInstance();
		cals1.set(Calendar.HOUR_OF_DAY, 9);
		cals1.set(Calendar.SECOND, 00);
		cals1.set(Calendar.MINUTE, 00);
		long cals_1 = cals1.getTimeInMillis();

		Calendar cals2 = Calendar.getInstance();
		cals2.set(Calendar.HOUR_OF_DAY, 10);
		cals2.set(Calendar.SECOND, 00);
		cals2.set(Calendar.MINUTE, 30);
		long cals_2 = cals2.getTimeInMillis();

		Calendar cals3 = Calendar.getInstance();
		cals3.set(Calendar.HOUR_OF_DAY, 14);
		cals3.set(Calendar.SECOND, 00);
		cals3.set(Calendar.MINUTE, 00);
		long cals_3 = cals3.getTimeInMillis();

		Calendar cals4 = Calendar.getInstance();
		cals4.set(Calendar.HOUR_OF_DAY, 15);
		cals4.set(Calendar.SECOND, 00);
		cals4.set(Calendar.MINUTE, 30);
		long cals_4 = cals4.getTimeInMillis();

		Calendar cals5 = Calendar.getInstance();
		cals5.set(Calendar.HOUR_OF_DAY, 16);
		cals5.set(Calendar.SECOND, 00);
		cals5.set(Calendar.MINUTE, 30);
		long cals_5 = cals5.getTimeInMillis();
		if (week > 0 && week <= 5) {
			if (currentTime<=cals0 && currentTime <= cals_1) {// 9:00 前提交的，当日 11:00 左右到帐；
				Calendar cld1 = Calendar.getInstance();
				cld1.set(Calendar.HOUR_OF_DAY, 11);
				cld1.set(Calendar.SECOND, 00);
				cld1.set(Calendar.MINUTE, 00);
				long cal1 = cld1.getTimeInMillis();
				Date date = new Date(cal1);
				ee.setPromptTime(formatter.format(date));
			} else if (currentTime > cals_1 && currentTime <= cals_2) {//10:30 前提交的，当日 12:00 左右到帐；
				Calendar cld1 = Calendar.getInstance();
				cld1.set(Calendar.HOUR_OF_DAY, 12);
				cld1.set(Calendar.SECOND, 00);
				cld1.set(Calendar.MINUTE, 00);
				long cal1 = cld1.getTimeInMillis();
				Date date = new Date(cal1);
				ee.setPromptTime(formatter.format(date));
			} else if (currentTime > cals_2 && currentTime <= cals_3) {//10:30-14:00 提交的，当日 17:00 左右到帐；
				Calendar cld1 = Calendar.getInstance();
				cld1.set(Calendar.HOUR_OF_DAY, 17);
				cld1.set(Calendar.SECOND, 00);
				cld1.set(Calendar.MINUTE, 00);
				long cal1 = cld1.getTimeInMillis();
				Date date = new Date(cal1);
				ee.setPromptTime(formatter.format(date));
			} else if (currentTime > cals_3 && currentTime <= cals_4) {//14:00-15:30提交的，当日17:30左右到帐
				Calendar cld1 = Calendar.getInstance();
				cld1.set(Calendar.HOUR_OF_DAY, 17);
				cld1.set(Calendar.SECOND, 00);
				cld1.set(Calendar.MINUTE, 30);
				long cal1 = cld1.getTimeInMillis();
				Date date = new Date(cal1);
				ee.setPromptTime(formatter.format(date));
			} else if (currentTime > cals_4 && currentTime <= cals_5) {//15:30-16:30提交的，当日18:30左右到帐
				Calendar cld1 = Calendar.getInstance();
				cld1.set(Calendar.HOUR_OF_DAY, 18);
				cld1.set(Calendar.SECOND, 00);
				cld1.set(Calendar.MINUTE, 30);
				long cal1 = cld1.getTimeInMillis();
				Date date = new Date(cal1);
				ee.setPromptTime(formatter.format(date));
			}else {// 16:30 后申请提现的，次日 10:30 左右到帐；
				Calendar cld1 = Calendar.getInstance();
				cld1.set(Calendar.HOUR_OF_DAY, 34);
				cld1.set(Calendar.SECOND, 00);
				cld1.set(Calendar.MINUTE, 30);
				long cal1 = cld1.getTimeInMillis();
				Date date = new Date(cal1);
				ee.setPromptTime(formatter.format(date));
			}
		} else if (week == 6) {//节假日申请打款，于最近一个工作日11:00到帐。
			Calendar cld1 = Calendar.getInstance();
			cld1.set(Calendar.HOUR_OF_DAY, 59);
			cld1.set(Calendar.SECOND, 00);
			cld1.set(Calendar.MINUTE, 00);
			long cal1 = cld1.getTimeInMillis();
			Date date = new Date(cal1);
			ee.setPromptTime(formatter.format(date));
		} else {//节假日申请打款，于最近一个工作日11:00到帐。
			Calendar cld1 = Calendar.getInstance();
			cld1.set(Calendar.HOUR_OF_DAY, 35);
			cld1.set(Calendar.SECOND, 00);
			cld1.set(Calendar.MINUTE, 00);
			long cal1 = cld1.getTimeInMillis();
			Date date = new Date(cal1);
			ee.setPromptTime(formatter.format(date));
		}
		if (!"0".equals(errCode)) {
			ee.setErrorMessage(msg);
			ee.setAuthentication(AuthenticationEnum.TOPAY_ACFAILED);
		} else {
			ee.setAuthentication(AuthenticationEnum.PENDINGVERIFICATION);
			// ee.setCreditCard(creditCard.replaceAll(" ", ""));//企业对公银行账户
			// ee.setSubbranch(subbranch);//银行开户支行
			// ee.setDepositBank(depositBank);//开户行名称
			// ee.setProvince(province);//账户所在省
			// ee.setCity(city);//账户所在市
		}
		
		ee.setToPayCount(ee.getToPayCount() + 1);
		enterpriseService.updateEnterprise(ee);
		logger.info("打款params:" + params);
		logger.info("打款msg:" + msg);
		logger.info("打款errCode:" + errCode);
	}

	@Override
	@Transactional
	public void cashVerification(BigDecimal cash) {
		Long enterpriseId = FinanceSessionContext.getEnterpriseId();
		String url = ConfigPropertites.getProperties("esign_url") + "/realname/rest/external/organ/payAuth";
		String projectSecret = ConfigPropertites.getProperties("PROJECT_SECRET");
		String projectId = ConfigPropertites.getProperties("PROJECTID");
		JSONObject params = new JSONObject();

		EnterpriseEntity ee = enterpriseService.inquireEnterprise(enterpriseId);

		params.put("serviceId", ee.getServiceId());// 实名认证成功或失效，需要重新发起实名认证请求
		params.put("cash", cash);// 打款金额
		String requestJson = params.toString();
		String signature = Secretkey.encrytSHA256(requestJson, projectSecret);
		Map<String, String> headMap = new HashMap<>();
		headMap.put("X-timevale-project-id", projectId);
		headMap.put("X-timevale-signature", signature);
		String responseText = HttpClientHelper.httpTest(url, requestJson, headMap);
		
		logger.info("打款验证params:" + params);
		logger.info("打款验证responseText:" + responseText);
		
		JSONObject paramObj = JSONObject.fromObject(responseText);
		String msg = paramObj.get("msg").toString();
		String errCode = paramObj.get("errCode").toString();
		ee.setCash(cash);
		if (!"0".equals(errCode)) {
			ee.setAuthentication(AuthenticationEnum.MONEY_ERROR);
			ee.setErrorMessage(msg);
		} else {
			ee.setAuthentication(AuthenticationEnum.ACSUCCESS);
			ee.setErrorMessage(msg);
		}
		enterpriseService.updateEnterprise(ee);
	}

	@Override
	@Transactional
	public void recertification(Long enterpriseId) {
		EnterpriseEntity ee = enterpriseService.inquireEnterprise(enterpriseId);
		ee.setErrorMessage("");
		ee.setAuthentication(AuthenticationEnum.NOTCERTIFIED);
		enterpriseService.updateEnterprise(ee);
	}
	@Override
	public String inquireEnterprisLists(Long enterpriseId){
		if (null == enterpriseId) {
			enterpriseId = FinanceSessionContext.getEnterpriseId();
		}
		EnterpriseEntity ee = enterpriseService.inquireEnterprise(enterpriseId);
		String ss=ee.getEnterpriseName();
		return ss;
	}

}
